<?php
/**
 * Created by PhpStorm.
 * User: 钊鑫
 * Date: 2019/1/23
 * Time: 9:55
 */
namespace app\api\controller;

use app\api\validate\Login as LoginValidate;
use app\api\validate\Register as RegisterValidate;
use app\api\validate\Sms as SmsValidate;
use app\api\service\Sms as SmsService;
use app\api\service\WxLogin as WxLoginService;
use app\api\model\Homeuser as HomeuserModel;
use think\facade\Cache;
use think\Session;

//Token类
class WxLogin extends Base
{
    //用户登录
    public function login(){
        $validate = new LoginValidate();
        $validate->goCheck();
        $post = $validate->getDataByRule(input('post.'));//过滤非验证器中的字段
        $post['password'] = MD5(MD5($post['password']));
        $result = HomeuserModel::where(['username'=>$post['username'],'password'=>$post['password']])->find();
        if($result) {
//            $usertoken = new WxTokenService($post['xcxcode'],$result['id']);
//            $usertoken = $usertoken->getToken();
//            if($usertoken) {
                return $this->successMessage(['msg'=>'登录成功！','token'=>'c05370c7ae3a021caec744958cb77e19','info'=>$result]);
//            }else {
//                    $this->errorMessage('同一用户只能授权一个小程序！');
//            }
        }else {
            $this->errorMessage('账号或密码错误');
        }
    }

    //用户注册
    public function register(){
        $validate = new RegisterValidate();
        $scene = (input('post.type') == '2') ? 'student' : 'teacher';//自定义场景
        $validate->scene($scene)->goCheck();
        $post = input('post.');//过滤非验证器中的字段
        $result =  WxLoginService::register($post);//对提交的数据进行逻辑处理验证
        if($result['status'] == 1) {
            $this->successMessage(['msg'=>'注册成功！','token'=>$result['msg']]);
        }else if($result['status'] == -1) {
            $this->errorMessage($result['msg']);
        }else {
            $this->errorMessage('其他未知错误，请重新注册！');
        }
    }

    //短信验证
    public function smsCode(){
        $validate = new SmsValidate();
        $validate->goCheck();
        $post = $validate->getDataByRule(input('post.'));//过滤非验证器中的字段
        $code = rand(1000, 9999);
//        $Sms = new SmsService();
//        $result = $Sms->sendSmsByAliyun($post['number'],['code'=>$code]);
        $result = array('status' => 1,'msg'=>'测试发送成功');
        if($result['status'] == '1') {
            session_start();//开启session会话
            $sign = session_id();
            $data['number'] = $post['number'];
            $data['code'] = $code;
            Cache::set($sign,$data,60);//一分钟过期
            return $this->successMessage(['data'=>$result['msg'].'，验证码为'.$code,'sign'=>$sign]);
        }else if($result['status'] == '-1') {
            $this->errorMessage($result['msg']);
        }else {
            $this->errorMessage('其他未知错误！');
        }
    }

}